/*	
	stencil - action script 3 isometric game engine.

	http://code.google.com/p/stencilas3/
	
	Copyright (c) 2010 Max Zhuravkov, All Rights Reserved.

	Permission is hereby granted, free of charge, to any person obtaining a copy of
	this software and associated documentation files (the "Software"), to deal in
	the Software without restriction, including without limitation the rights to
	use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
	of the Software, and to permit persons to whom the Software is furnished to do
	so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in all
	copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
	SOFTWARE.
*/
package stencil.core.engine 
{
	import flash.events.EventDispatcher;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.utils.Dictionary;
	import stencil.core.errors.ArgumentIsNullError;
	import stencil.core.errors.NotImplementedMethodError;
	import stencil.core.engine.camera.CameraModeSettings;
	import stencil.core.engine.camera.ICameraMode;
	
	/**
	 * 
	 * @author Max Zhuravkov
	 */
	public class CameraModel extends EventDispatcher implements ICameraModel {
		
		private var _grid:IGrid;
		
		private var _viewPort:Rectangle;
		
		private var _extraSpace:Rectangle = new Rectangle();
		
		private var _followedObject:IGameObject;
		
		private var _visibleArea:Rectangle;
		
		private var _displays:Array = [];
		
		private var _modes:Dictionary = new Dictionary();
		
		private var _activeMode:String;
		
		protected var flagFirstUpdate:Boolean = true;
		
		protected var flagViewPortChanged:Boolean;
		
		
		//------------------------------------------------------------------------------------------------
		// Constructor
		//------------------------------------------------------------------------------------------------
		
		public function CameraModel(grid:IGrid) {
			super();
			this._grid = grid;
		}
		
		//------------------------------------------------------------------------------------------------
		// Public methods
		//------------------------------------------------------------------------------------------------
		
		/**
		 * @inheritDoc
		 */
		public function set extraSpace(value:Rectangle):void {
			if (this._extraSpace && this._extraSpace.equals(value)) {
				return;
			}
			if (!this._extraSpace) {
				this._extraSpace = new Rectangle();
			}
			this._extraSpace.width = value.width;
			this._extraSpace.height = value.height;
		}
		
		public function get extraSpace():Rectangle {
			return this._extraSpace;
		}
		
		/**
		 * @inheritDoc
		 */
		public function set viewPort(value:Rectangle):void
		{
			if (this._viewPort && this._viewPort.equals(value)) {
				return;
			}
			
			if (value.width <= 0 || value.height < 0) {
				throw new ArgumentError("Viewport dimensions should be greater then zero.")
			}
			
			if (!this._viewPort) {
				this._viewPort = new Rectangle();
			}
			this._viewPort.width = value.width;
			this._viewPort.height = value.height;
			
			if (!this._visibleArea) {
				this._visibleArea = new Rectangle();
				this._visibleArea.width = value.width;
				this._visibleArea.height = value.height;
			}
			
			this.flagViewPortChanged = true;
		}
		
		
		public function get viewPort():Rectangle {
			return this._viewPort;
		}
		
		/**
		 * @inheritDoc
		 */
		public function get visibleArea():Rectangle {
			return this._visibleArea;
		}
		
		public function get grid():IGrid {
			return this._grid;
		}
		
		/**
		 * @inheritDoc
		 */
		public function set activeMode(value:String):void {
			if (this._activeMode == value) {
				return;
			}
			if (value && !this._modes[value]) {
				throw new ArgumentError("No mode with name '" + value + "' has been registered.")
			}
			var previousMode:ICameraMode = null;
			
			if (this._activeMode) {
				previousMode = this._modes[this._activeMode];
				previousMode.deactive(this);
			}
			
			this._activeMode = value;
			
			if (value) {
				var mode:ICameraMode = this._modes[value];
				
				mode.activate(this, previousMode);
			}
		}
		
		public function get activeMode():String {
			return this._activeMode;
		}
		
		//------------------------------------------------------------------------------------------------
		// Public methods
		//------------------------------------------------------------------------------------------------
		
		/**
		 * @inheritDoc
		 */
		public function addMode(name:String, mode:ICameraMode, settings:CameraModeSettings, setAsActive:Boolean = false):void {
			if (!name) {
				throw new ArgumentIsNullError("name");
			}
			if (!mode) {
				throw new ArgumentIsNullError("mode");
			}
			if (this._modes[name]) {
				throw new ArgumentError("Mode with name '" + name + "' has been already registered.")
			}
			if (!settings) {
				throw new ArgumentIsNullError("settings");
			}
			this._modes[name] = mode;
			
			mode.attached();
			mode.apply(settings);
			
			if (setAsActive) {
				this.activeMode = name;
			}
		}
		
		/**
		 * @inheritDoc
		 */
		public function changeModeSettings(name:String, settings:CameraModeSettings):void {
			if (!this._modes[name]) {
				throw new ArgumentError("No mode with name '" + name + "' has been registered.")
			}
			if (!settings) {
				throw new ArgumentIsNullError("settings");
			}
			var mode:ICameraMode = this._modes[name];
			mode.apply(settings);
		}
		
			
		/**
		 * @inheritDoc
		 */
		public function removeMode(name:String):void {
			if (!this._modes[name]) {
				throw new ArgumentError("No mode with name '" + name + "' has been registered.")
			}
			var mode:ICameraMode = this._modes[name]
			if (this.activeMode == name) {
				this.activeMode = null;
			}
			mode.detached();
			delete this._modes[name];
		}
		
		/**
		 * @inheritDoc
		 */
		public function addDisplay(display:ICameraDisplay):void {
			if (!display) {
				throw new ArgumentIsNullError("display")
			}
			
			if(this._displays.indexOf(display) == -1){
				this._displays.push(display);
			}
		}
		
		/**
		 * @inheritDoc
		 */
		public function removeDisplay(display:ICameraDisplay):void {
			if (!display) {
				throw new ArgumentIsNullError("display")
			}
			
			var index:int = this._displays.indexOf(display);
			
			if (index >= 0) {
				this._displays.splice(index, 1);
			}
		}
		
		/**
		 * @inheritDoc
		 */
		public function hasDisplay(display:ICameraDisplay):Boolean {
			if (!display) {
				throw new ArgumentIsNullError("display")
			}
			
			return this._displays.indexOf(display) >= 0;
		}
		
		/**
		 * @inheritDoc
		 */
		public final function update(dt:Number):Boolean {
			var mode:ICameraMode = this.activeMode ? this._modes[this.activeMode] : null;
			var changed:Boolean  = this.updateCamera(mode, dt);
			
			if (mode && changed) {
				this._visibleArea.x = mode.visibleArea.x;
				this._visibleArea.y = mode.visibleArea.y;
				this._visibleArea.width = mode.visibleArea.width;
				this._visibleArea.height = mode.visibleArea.height;
			}
			
			if (this.flagFirstUpdate) {
				this.flagFirstUpdate = false;
			}
			
			if (this.flagViewPortChanged) {
				this.flagViewPortChanged = false;
			}
			return changed;
		}
		
		/**
		 * @inheritDoc
		 */
		public final function updatePosition(areaChanged:Boolean):void {
			var mode:ICameraMode = this.activeMode ? this._modes[this.activeMode] : null;
			this.updateCameraPosition(mode, areaChanged);
			
			if (mode) {
				var dx:Number = mode.displayPosition.x;
				var dy:Number = mode.displayPosition.y;
				
				for each(var display:ICameraDisplay in this._displays) {
					display.displayAt(dx, dy);
				}
			}
			
		}
		
		//------------------------------------------------------------------------------------------------
		// Protected methods
		//------------------------------------------------------------------------------------------------
		
		protected function updateCamera(mode:ICameraMode, dt:Number):Boolean {
			if (mode) {
				if(this.flagViewPortChanged){
					mode.setViewPort(this.viewPort);
				}
				
				mode.calculationPhase(dt);
				
				return this.flagFirstUpdate || !mode.visibleArea.equals(this.visibleArea);
			}else {
				return this.flagFirstUpdate;
			}
		}
		
		protected function updateCameraPosition(mode:ICameraMode, areaChanged:Boolean):void {
			if (mode) {
				mode.updatePhase(areaChanged);
			}
			
		}
	}

}